//
//  MYPreviewController.swift
//  zhengwutong
//
//  Created by wang shuguan on 2020/2/22.
//  Copyright © 2020 wang shuguan. All rights reserved.
//

import UIKit
import QuickLook
extension NSNotification.Name{
    /// 预览文件的删除事件
    static let previewDel = NSNotification.Name(rawValue: "previewDelNotification")
    static let previewDismiss = NSNotification.Name(rawValue: "previewDismissNotification")
    static let previewItemChanged = NSNotification.Name(rawValue: "previewItemChangedNotification")
    static let openFiles = NSNotification.Name(rawValue: "openFilesNotification")
}
class PreviewControllerToolbar: UIToolbar {
    override func setItems(_ items: [UIBarButtonItem]?, animated: Bool) {
        super.setItems([UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add))], animated: false)
    }
    @objc func add(){
        NotificationCenter.default.post(name: .openFiles, object: nil, userInfo: nil)
    }
}
class PreviewNavigationController: UINavigationController {
    var index:Int?
    var hasDel = false
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(previewItemChanged), name: .previewItemChanged, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(doneButtonTapped), name: .previewDismiss, object: nil)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let controller = viewControllers.first {
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target:self, action:#selector(doneButtonTapped))
            controller.navigationItem.leftBarButtonItem = doneButton
            if hasDel {
                controller.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(delButtonTapped))
            }else{
                controller.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
            }
            index = 0
        }
    }
    @objc func doneButtonTapped() -> Void {
        dismiss(animated: true, completion: {[weak self] in
            self?.setViewControllers([], animated: false)
        })
    }
    @objc func delButtonTapped() -> Void {
        NotificationCenter.default.post(name: .previewDel, object: index)
    }
    deinit {
        print("PreviewNavigationController deinit")
        NotificationCenter.default.removeObserver(self)
    }
    @objc func previewItemChanged(no:Notification){
        if let i = no.object as? String{
            print(i)
            index = Int(i.components(separatedBy: "/").first ?? "0")
        }
    }
}
class PreviewItem:NSObject, QLPreviewItem {
    var previewItemURL: URL?
    init(_ url:URL?) {
        self.previewItemURL = url
    }
}
class MYPreviewController: QLPreviewController,QLPreviewControllerDelegate,QLPreviewControllerDataSource {
    var files:[URL] = []
    var index = 0
    var delAction:((Int)->Void) = {_ in}
    var importAction:((Int)->Void) = {_ in}
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.delegate = self
        self.dataSource = self
        NotificationCenter.default.post(name: .previewItemChanged, object: "\(0)/\(files.count)")
        NotificationCenter.default.addObserver(self, selector: #selector(del), name: .previewDel, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(openFiles), name: .openFiles, object: nil)
    }
    @objc func openFiles(){
        let i = self.currentPreviewItemIndex
        importAction(i)
        NotificationCenter.default.post(name: .previewDismiss, object: nil)
    }
    deinit {
        print("MYPreviewController deinit")
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if self.currentPreviewItemIndex >= 0,self.currentPreviewItemIndex != index {
            index = self.currentPreviewItemIndex
            NotificationCenter.default.post(name: .previewItemChanged, object: "\(index)/\(files.count)")
        }
    }
    @objc func del() {
        let i = self.currentPreviewItemIndex
        delAction(i)
        self.files.remove(at: i)
        if self.files.isEmpty {
            NotificationCenter.default.post(name: .previewDismiss, object: nil)
        }else{
            self.reloadData()
            DispatchQueue.main.after(0.2) {[weak self] in

                if let SSelf = self{
                    if let navc = SSelf.navigationController?.navigationController as? PreviewNavigationController {
                        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target:navc, action:#selector(PreviewNavigationController.doneButtonTapped))
                        SSelf.navigationItem.leftBarButtonItem = doneButton
                    }
                    NotificationCenter.default.post(name: .previewItemChanged, object: "\(SSelf.index)/\(SSelf.files.count)")
                }
            }
        }
    }
    //MARK: - QLPreviewControllerDelegate methods
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return files.count
    }
    
    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        return PreviewItem(files[index])
    }
}
